package com.cskaoyan.processor;

import com.cskaoyan.fandian.KFC;
import com.cskaoyan.fandian.MC;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author stone
 * @date 2022/09/30 16:32
 */
@Component
public class ChickenProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return Enhancer.create(bean.getClass(), new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                /*if (bean instanceof KFC || bean instanceof MC) {
                    return executeKFCHb(method, objects, bean);
                }*/
                if ("xianglaHb".equals(method.getName())) {//切入点
                    System.out.println("多放点肉");
                }
                if (bean instanceof KFC) {//切入点
                    return executeKFCHb(method, objects, bean);
                }
                if (bean instanceof MC) {//切入点
                    return executeMCHb(method, objects, bean);
                }

                return method.invoke(bean, objects);
            }
        });
        //return bean;
    }

    private Object executeKFCHb(Method method, Object[] objects, Object bean) throws IllegalAccessException, InvocationTargetException {
        System.out.println("西红柿片、酸黄瓜、生菜");
        Object invoke = method.invoke(bean, objects);
        System.out.println("芝士片、生菜");
        return invoke;
    }
    private Object executeMCHb(Method method, Object[] objects, Object bean) throws IllegalAccessException, InvocationTargetException {
        System.out.println("芝士片、生菜");
        Object invoke = method.invoke(bean, objects);
        System.out.println("西红柿片、酸黄瓜");
        return invoke;
    }
}
